<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="150px">
      <el-form-item label="机构单位" prop="unitName">
        <el-input
          v-model="queryParams.unitName"
          placeholder="请输入机构单位名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库年份" prop="storYear">
        <el-input
          v-model="queryParams.storYear"
          placeholder="请输入入库年份"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单位有无问题" prop="isUnit" style="width: 342px">
        <el-select v-model="queryParams.isUnit" placeholder="请选择单位有无问题" clearable>
          <el-option label="有问题" value="0" />
          <el-option label="无问题" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="供应商有无问题" prop="isSupplier" style="width: 342px">
        <el-select v-model="queryParams.isSupplier" placeholder="请选择供应商有无问题" clearable>
          <el-option label="有问题" value="0" />
          <el-option label="无问题" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="数据整体有无问题" prop="noWrong" style="width: 342px">
        <el-select v-model="queryParams.noWrong" placeholder="请选择导入有无问题" clearable>
          <el-option label="有问题" value="0" />
          <el-option label="无问题" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['work:money:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['work:money:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button 
          type="info" 
          plain 
          icon="el-icon-upload2" 
          size="mini" 
          @click="handleImport" 
          v-hasPermi="['work:money:add']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['work:money:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="moneyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" width="55" align="center" prop="ids" />
      <el-table-column label="入库单位" align="center" prop="unitName" />
      <el-table-column label="入库供应商" align="center" prop="supplierName" />
      <el-table-column label="入库年份" width="80" align="center" prop="storYear" />
      <el-table-column label="01月" width="80" align="center" prop="storMoney01" />
      <el-table-column label="02月" width="80" align="center" prop="storMoney02" />
      <el-table-column label="03月" width="80" align="center" prop="storMoney03" />
      <el-table-column label="04月" width="80" align="center" prop="storMoney04" />
      <el-table-column label="05月" width="80" align="center" prop="storMoney05" />
      <el-table-column label="06月" width="80" align="center" prop="storMoney06" />
      <el-table-column label="07月" width="80" align="center" prop="storMoney07" />
      <el-table-column label="08月" width="80" align="center" prop="storMoney08" />
      <el-table-column label="09月" width="80" align="center" prop="storMoney09" />
      <el-table-column label="10月" width="80" align="center" prop="storMoney10" />
      <el-table-column label="11月" width="80" align="center" prop="storMoney11" />
      <el-table-column label="12月" width="80" align="center" prop="storMoney12" />
      <el-table-column label="数据有无问题" width="80" align="center" prop="noWrong" >
        <template #default="scope">
          <span>{{ scope.row.noWrong === '0' ? '有问题' : (scope.row.noWrong === '1' ? '没问题' : scope.row.noWrong) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['work:money:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['work:money:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改入库金额对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="moneyRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <div v-if="form.noWrong==='1'" style="color:blue;margin:5px auto; display: block; text-align: center">
              注意：当前页面整体都没有问题，可以正常使用！
            </div>
            <div v-else style="color:red;margin:5px auto; display: block; text-align: center">
              注意：当前页面存在不标准数据类型，请尽快修改！
            </div>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库单位" prop="unitId">
              <el-select v-model="form.unitId" placeholder="请选择入库单位" filterable @change="handleUnitChange">
                <el-option
                  v-for="unit in unitOptions"
                  :key="Number(unit.ids)"
                  :label="unit.unitName"
                  :value="Number(unit.ids)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="导入单位" prop="unitName">
              <el-input v-model="form.unitName" placeholder="请输入入库单位名称" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div v-if="form.isUnit==='1'" style="color:blue;margin:5px auto; display: block; text-align: center">
              注意：当前入库单位与导入单位一致！
            </div>
            <div v-else style="color:red;margin:5px auto; display: block; text-align: center">
              注意：当前入库单位与导入单位不一致！
            </div> 
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库供应商" prop="supplierId">
              <el-select v-model="form.supplierId" placeholder="请选择入库供应商" filterable @change="handleSupplierChange" >
                <el-option
                  v-for="supplier in supplierOptions"
                  :key="Number(supplier.ids)"
                  :label="supplier.supplierName"
                  :value="Number(supplier.ids)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="导入供应商" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请输入导入供应商名称" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div v-if="form.isSupplier==='1'" style="color:blue;margin:5px auto; display: block; text-align: center">
              注意：当前备注与字典备注一致！
            </div>
            <div v-else style="color:red;margin:5px auto; display: block; text-align: center">
              注意：当前备注与字典备注不一致！
            </div>
          </el-col>
          <el-col :span="24">
            <el-form-item label="入库年份" prop="storYear">
              <el-input-number v-model="form.storYear" placeholder="请输入入库年份" style="width: 300px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="01月入库金额" prop="storMoney01">
              <el-input-number v-model="form.storMoney01" placeholder="请输入01月入库金额" style="width: 300px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="02月入库金额" prop="storMoney02">
              <el-input-number v-model="form.storMoney02" placeholder="请输入02月入库金额" style="width: 300px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="03月入库金额" prop="storMoney03">
              <el-input-number v-model="form.storMoney03" placeholder="请输入03月入库金额" style="width: 300px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="04月入库金额" prop="storMoney04">
              <el-input-number v-model="form.storMoney04" placeholder="请输入04月入库金额" style="width: 300px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="05月入库金额" prop="storMoney05">
              <el-input-number v-model="form.storMoney05" placeholder="请输入05月入库金额" style="width: 300px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="06月入库金额" prop="storMoney06">
              <el-input-number v-model="form.storMoney06" placeholder="请输入06月入库金额" style="width: 300px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="07月入库金额" prop="storMoney07">
              <el-input-number v-model="form.storMoney07" placeholder="请输入07月入库金额" style="width: 300px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="08月入库金额" prop="storMoney08">
              <el-input-number v-model="form.storMoney08" placeholder="请输入08月入库金额" style="width: 300px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="09月入库金额" prop="storMoney09">
              <el-input-number v-model="form.storMoney09" placeholder="请输入09月入库金额" style="width: 300px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="10月入库金额" prop="storMoney10">
              <el-input-number v-model="form.storMoney10" placeholder="请输入10月入库金额" style="width: 300px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="11月入库金额" prop="storMoney11">
              <el-input-number v-model="form.storMoney11" placeholder="请输入11月入库金额" style="width: 300px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="12月入库金额" prop="storMoney12">
              <el-input-number v-model="form.storMoney12" placeholder="请输入12月入库金额" style="width: 300px" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="upload.titleImport" :visible.sync="upload.openImport" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.openImport = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Money">
import { ref, reactive, onMounted } from 'vue';
import { ElForm, ElMessageBox, ElMessage } from 'element-plus';
import { getToken } from "@/utils/auth";
import { listMoney, getMoney, delMoney, addMoney, updateMoney } from "@/api/work/money";
import { findAllUnitList } from "@/api/work/unit";
import { findAllSupplierList } from "@/api/work/supplier";


const { proxy } = getCurrentInstance();

const moneyList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const queryFormRef = ref();
const moneyRef = ref();
const uploadRef = ref();
// 机构单位选项
const unitOptions = ref([]);
// 供应商选项
const supplierOptions = ref([]);

const data = reactive({
  // 表单参数
  form: {},
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    unitName: null,
    isUnit: null,
    supplierName: null,
    isSupplier: null,
    storYear: null,
    noWrong: null,
  },
  // 表单校验
  rules: {
    unitId: [
      { required: true, message: "入库单位不能为空", trigger: "blur" }
    ],
    unitName: [
      { required: true, message: "导入单位不能为空", trigger: "blur" }
    ],
    isUnit: [
      { required: true, message: "导入单位是否正确不能为空", trigger: "change" }
    ],
    supplierId: [
      { required: true, message: "入库供应商不能为空", trigger: "blur" }
    ],
    supplierName: [
      { required: true, message: "导入供应商不能为空", trigger: "blur" }
    ],
    isSupplier: [
      { required: true, message: "导入供应商是否正确不能为空", trigger: "change" }
    ],
    storYear: [
      { required: true, message: "入库年份不能为空", trigger: "change" },
      { validator: (rule, value, callback) => {
            if (value && (!/^\d{4}$/.test(value) || value < 1900 || value > 2200)) {
              callback(new Error('请输入4位有效年份数字(1900-2200)'));
            } else {
              callback();
            }
          }, trigger: 'change' }
    ],
    noWrong: [
      { required: true, message: "导入整体是否有错不能为空", trigger: "blur" }
    ],
  },
  // 导入参数
  upload: {
    // 是否显示弹出层（导入弹窗）
    openImport: false,
    // 弹出层标题（自己填写）
    titleImport: "",
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken() },
    // 上传的地址,即后端接口地址
    url: import.meta.env.VITE_APP_BASE_API + "/work/money/importData"
  }
});

const { queryParams, form, rules, upload } = toRefs(data);

/** 获取机构单位选项 */
function getUnitOptions() {
  findAllUnitList().then(response => {
    unitOptions.value = response.data || [];
  });
}

/** 机构单位选择变更处理 */
function handleUnitChange(value) {
  // 根据选中的unitId查找对应的unitName
  const selectedUnit = unitOptions.value.find(item => item.ids === value);
  if (selectedUnit) {
    form.value.unitName = selectedUnit.unitName;
    form.value.isUnit = '1';
  } else {
    form.value.unitName = '';
    form.value.isUnit = '0';
  }
  isWrong();
}

/** 获取供应商选项 */
function getSupplierOptions() {
  findAllSupplierList().then(response => {
    supplierOptions.value = response.data || [];
  });
}

/** 供应商选择变更处理 */
function handleSupplierChange(value) {
  // 根据选中的supplierId查找对应的supplierName
  const selectedSupplier = supplierOptions.value.find(item => item.ids === value);
  if (selectedSupplier) {
    form.value.supplierName = selectedSupplier.supplierName;
    form.value.isSupplier = '1';
  } else {
    form.value.supplierName = '';
    form.value.isSupplier = '0';
  }
  isWrong();
}

/** 机构单位和供应商变更后调用该方法，判断是否一致了 */
function isWrong() {
  if(form.value.isUnit==='1' && form.value.isSupplier==='1'){
    form.value.noWrong = '1';
  }else{
    form.value.noWrong = '0';
  }
}

/** 查询入库金额列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  listMoney(queryParams.value).then(response => {
    moneyList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    ids: null,
    unitId: null,
    unitName: null,
    isUnit: null,
    supplierId: null,
    supplierName: null,
    isSupplier: null,
    storYear: null,
    storMoney01: null,
    storMoney02: null,
    storMoney03: null,
    storMoney04: null,
    storMoney05: null,
    storMoney06: null,
    storMoney07: null,
    storMoney08: null,
    storMoney09: null,
    storMoney10: null,
    storMoney11: null,
    storMoney12: null,
    noWrong: null,
    addTime: null,
    upTime: null
  };
  proxy.resetForm("moneyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryFormRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.ids);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加入库金额";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.ids || ids.value[0];
  getMoney(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改入库金额";
  });
}

/** 提交按钮 */
function submitForm() {
  moneyRef.value.validate(valid => {
    if (valid) {
      if (form.value.ids != null) {
        updateMoney(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMoney(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const idss = row.ids || ids.value;
  ElMessageBox.confirm('是否确认删除入库金额编号为"' + idss + '"的数据项？', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(function() {
    return delMoney(idss);
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('work/money/export', {
    ...queryParams.value
  }, `storMoney_${new Date().getTime()}.xlsx`);
}

/**导入excel表*/
function handleImport() {
  upload.value.titleImport = "导入入库金额表";
  upload.value.openImport = true;
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download('work/money/importTemplate', {
    ...queryParams.value
  }, `入库金额模板_${new Date().getTime()}.xlsx`);
}

// 文件上传中处理
function handleFileUploadProgress(event, file, fileList) {
  upload.value.isUploading = true;
}

// 文件上传成功处理
function handleFileSuccess(response, file, fileList) {
  upload.value.openImport = false;
  upload.value.isUploading = false;
  uploadRef.value.clearFiles();
  ElMessageBox.alert(response.msg, "导入结果", {
    dangerouslyUseHTMLString: true
  });
  getList();
}

// 提交上传文件
function submitFileForm() {
  uploadRef.value.submit();
}

onMounted(() => {
  getList();
  getUnitOptions();
  getSupplierOptions();
});
</script>
